using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;

namespace ACME.Northwind.DALProxy.Extensions
{
	/// <summary>
	/// This is a set of extensions for the Category DAL/DTO object
	/// </summary>
	public static partial class CategoryExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this Category item, CategoryDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The Category DTO cannot be null.");
			if (item == null) throw new Exception("The Category item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			dr["CategoryName"] = dtoItem.CategoryName;
			dr["CategoryID"] = dtoItem.CategoryId;
			if (dtoItem.Picture == null) dr["Picture"] = System.DBNull.Value;
			else dr["Picture"] = dtoItem.Picture;
			if (dtoItem.Description == null) dr["Description"] = System.DBNull.Value;
			else dr["Description"] = dtoItem.Description;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="categoryCollection">The source DAL collection.</param>
		public static void Fill(this List<CategoryDTO> list, CategoryCollection categoryCollection)
		{
			if (categoryCollection == null) throw new Exception("The Category collection cannot be null.");
			if (list == null) list = new List<CategoryDTO>();
			foreach (Category item in categoryCollection)
			{
				CategoryDTO newItem = new CategoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this CategoryDTO dtoItem, Category item)
		{
			if (dtoItem == null) throw new Exception("The Category DTO cannot be null.");
			if (item == null) throw new Exception("The Category item cannot be null.");
			dtoItem.CategoryName = item.CategoryName;
			dtoItem.CategoryId = item.CategoryId;
			dtoItem.Picture = item.Picture;
			dtoItem.Description = item.Description;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<CategoryDTO> list)
		{
			if (list == null) list = new List<CategoryDTO>();
			CategoryCollection retval = CategoryCollection.RunSelect();
			foreach (Category item in retval)
			{
				CategoryDTO newItem = new CategoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<CategoryDTO> list, Expression<Func<CategoryQuery, bool>> where)
		{
			if (list == null) list = new List<CategoryDTO>();
			list.Fill(CategoryCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<CategoryDTO> RunSelect(this List<CategoryDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<CategoryDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			Category.FieldNameConstants sortField;
			try
			{
				sortField = (Category.FieldNameConstants)Enum.Parse(typeof(Category.FieldNameConstants), sortColumn);
			}
			catch
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<CategoryDTO> retVal = new PagedQueryResults<CategoryDTO>();
			CategoryPaging paging = new CategoryPaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new CategoryPagingFieldItem(sortField, ascending));

			CategoryCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = CategoryCollection.RunSelect(x => true, paging);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "Category");
				dalList = (CategoryCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<CategoryDTO>();
			foreach (Category item in dalList)
			{
				CategoryDTO newItem = new CategoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<CategoryDTO> list, string linq)
		{
			if (list == null) list = new List<CategoryDTO>();

			CategoryCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = CategoryCollection.RunSelect(x => true);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.Northwind.Business", "Category");
				dalList = (CategoryCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<CategoryDTO>();
			foreach (Category item in dalList)
			{
				CategoryDTO newItem = new CategoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static CategoryDTO Persist(this CategoryDTO category)
		{
			if (category == null) throw new Exception("The Category DTO cannot be null.");
			//Find this object and if not exists, create a new one
			Category newItem = null;
			CategoryCollection newCollection = null;

			bool isIdentityChecked = false;
			isIdentityChecked = true;
			if(isIdentityChecked)
			{
				if (category.CategoryId > 0)
				{
					newItem = ACME.Northwind.Business.Objects.Category.SelectUsingPK(category.CategoryId);
					newCollection = newItem.ParentCollection;
				}
				else
				{
					if (category.CategoryId == 0) category.CategoryId = -1;
					newCollection = new CategoryCollection();
					newItem = newCollection.NewItem();
				}
			}
			else
			{
				newItem = ACME.Northwind.Business.Objects.Category.SelectUsingPK(category.CategoryId);
				if (newItem == null)
				{
					newCollection = new CategoryCollection();
					newItem = newCollection.NewItem();
				}
				else
				{
					newCollection = newItem.ParentCollection;
				}
			}

			//Populate the DAL and perist
			newItem.Fill(category);
			if (!newItem.IsParented) newCollection.AddItem(newItem);
			newCollection.Persist();

			//Re-populate the passed-in object from the DAL
			category.Fill(newItem);
			return category;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<CategoryDTO> categoryList)
		{
			if (categoryList == null) throw new Exception("The Category DTO list cannot be null.");
			//Get all objects from the database that match PK
			CategoryCollection categoryCollection = new CategoryCollection();
			List<CategoryPrimaryKey> keyList = new List<CategoryPrimaryKey>();
			foreach (CategoryDTO dto in categoryList)
			{
				keyList.Add(new CategoryPrimaryKey(dto.CategoryId));
			}			
			categoryCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.CategorySelectByPks(keyList));
			categoryCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (CategoryDTO dto in categoryList)
			{
				Category category = (from x in (IEnumerable<Category>)categoryCollection
					where x.CategoryId == dto.CategoryId
					select x).FirstOrDefault();

				if (category == null) category = categoryCollection.NewItem();
				category.Fill(dto);
				if (!category.IsParented) categoryCollection.AddItem(category);
			}
			categoryCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<CategoryDTO> deletedList = new List<CategoryDTO>();
			foreach (CategoryDTO dto in categoryList)
			{
				Category category = (from x in (IEnumerable<Category>)categoryCollection
					where x.CategoryId == dto.CategoryId
					select x).FirstOrDefault();

				if (category != null) dto.Fill(category);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (CategoryDTO dto in deletedList)
			{
				categoryList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region Category Select by Column

		#endregion

		#region Category SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static bool SelectUsingPK(this CategoryDTO category, int categoryid)
		{
			Category item = ACME.Northwind.Business.Objects.Category.SelectUsingPK(categoryid);
			if (item == null) return false;
			category.Fill(item);
			return true;
		}

		#endregion

		#region Category Select By Foreign Key

		#endregion

		#region Category Delete

		/// <summary>
		/// Delete the specified item
		/// </summary>
		public static bool Delete(this CategoryDTO category)
		{
			Category item = ACME.Northwind.Business.Objects.Category.SelectUsingPK(category.CategoryId);
			if (item == null) return false;
			item.Delete();
			item.Persist();
			return true;
		}

		#endregion
	}

}
